package com.facotry.controller;

import com.facotry.entity.FacUser;
import com.facotry.service.FacUserService;
import com.facotry.util.R;
import com.facotry.util.RedisUtil;
import com.facotry.util.RsaUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static net.sf.jsqlparser.util.validation.metadata.NamedObject.user;

/**
 * --- 代码敲烂 月薪过万 ---
 *
 * @author 崔瑜航
 * @date 2024/7/22
 * @desc
 */
@RestController
@RequestMapping("/user")
public class factoryUserController {


    @Autowired
    private FacUserService facUserService;
    //获取RedisUtil对象
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 登录
     */
    @PostMapping("/login")
    public R login(@RequestBody FacUser facUser) throws Exception {

        //浏览器解密
        System.out.println("----------" + facUser.getPassword());
        String pwd = RsaUtils.decryptByPrivateKey(facUser.getPassword());
        facUser.setPassword(pwd);
        System.out.println("============== " + pwd);
        //获得用户信息
        FacUser user = facUserService.login(facUser);



        if (user != null) {
            //1 登陆成功，生成令牌
            String token = UUID.randomUUID( ).toString( ).replace("-", "");
            // 2 已令牌为key,对象信息为value存储到redis
                // key形如: user:34j34h53j4hj36
                // key形如: user:56j747b65756lk
                // value是对象,已经配置value使用jackson2Json将对象转成JSON字符串
            //3 设置token失效时间
            redisUtil.setCacheObject("user:"+token,user,1, TimeUnit.MINUTES);

            //创建一个HasMap存储token
            HashMap<String, String> map = new HashMap<>();
            map.put("token",token);
            //4 将存储的token返回给前端方便后期发请求
            return R.ok(map);
        }
        return R.fail();
    }

    /*退出登录*/
    @GetMapping("/logout")
    public R logout(String token) {

        redisUtil.deleteObject("user:"+token);
        return R.ok();
    }


    /*获得用户信息*/
        @GetMapping("info")
    public R getUserInfo(String token) {
            FacUser facUser = redisUtil.getCacheObject("user:" + token);
            return R.ok(facUser);
    }
}
